#!/bin/bash
SOURCE_DATE_EPOCH=$(date +'%s')
if ! type -p gettext >/dev/null; then
	gettext() {
		printf "%s\n" "$@"
	}
fi

write_kv_pair() {
	local key="$1"
	shift

	for val in "$@"; do
		if [[ $val = *$'\n'* ]]; then
			error "Invalid value for $key $val"
			exit $E_PKGBUILD_ERROR
		fi
		printf "%s = %s\n" "$key" "$val"
	done
}

list_package_files() {
	(
		export LC_COLLATE=C
		shopt -s dotglob globstar
		# bash 5.0 only works with combo directory + file globs
		printf '%s\0' **/*
	)
}

__write_pkginfo() {
	#Create .PKGINFO
	echo -e "# Generated by unibuild"
	echo -e "# using $(fakeroot -v)" 
	echo -e "pkgname = $name" 
	echo -e "pkgbase = $name"
	echo -e "pkgver = $version-$release"
	echo -e "pkgdesc = $description" 
	echo -e "url = $url" 
	echo -e "builddate = $SOURCE_DATE_EPOCH" 
	echo -e "packager = $maintainer" 
	echo -e "size = $(du -sb $INSTALLDIR | cut -f1)" 
	echo -e "arch = $arch" 
	echo -e "license = $license" 
	write_kv_pair "replaces"    "${replaces[@]}"
	write_kv_pair "group"       "${groups[@]}"
	write_kv_pair "conflict"    "${conflicts[@]}"
	write_kv_pair "provides"    "${provides[@]}"
	write_kv_pair "backup"      "${backup[@]}"
	write_kv_pair "depend"      "${depends[@]}"
	write_kv_pair "optdepend"   "${optdepends[@]//+([[:space:]])/ }"
	write_kv_pair "makedepend"  "${builddepends[@]}"
	write_kv_pair "checkdepend" "${checkdepends[@]}"
}

__write_buildinfo() {
	#Create .BUILDINFO
	echo -e "format = 2" >> $PKGDIR/.BUILDINFO
	echo -e "pkgname = $name" >> $PKGDIR/.BUILDINFO
	echo -e "pkgbase = $name" >> $PKGDIR/.BUILDINFO
	echo -e "pkgver = $version-$release" >> $PKGDIR/.BUILDINFO
	echo -e "pkgarch = $arch" >> $PKGDIR/.BUILDINFO
	local sum="$(sha256sum "$CURDIR/$unibuild_file")"
	sum=${sum%% *}
	echo -e "pkgbuild_sha256sum = $sum" >> $PKGDIR/.BUILDINFO 
	echo -e "packager = $maintainer" >> $PKGDIR/.BUILDINFO
	echo -e "builddate = $SOURCE_DATE_EPOCH" >> $PKGDIR/.BUILDINFO 
	echo -e "builddir = $BUILDDIR" >> $PKGDIR/.BUILDINFO


	local pkginfos_parsed=($(LC_ALL=pkexec sh -c "pacman -Qi" | awk -F': ' '\
		/^Name .*/ {printf "%s", $2} \
		/^Version .*/ {printf "-%s", $2} \
		/^Architecture .*/ {print "-"$2} \
		'))
	write_kv_pair "installed" "${pkginfos_parsed[@]}"
}

__create_install_script() {
    if [ -f "$CURDIR/$install" ]; then
        cat $CURDIR/$install >> $PKGDIR/.INSTALL
    fi
}



_create_metadata(){
	__write_pkginfo >> $PKGDIR/.PKGINFO
	__write_buildinfo >> $PKGDIR/.BUILDINFO
	__create_install_script
}

_package(){
	cp -prfv $INSTALLDIR/* $PKGDIR/
	cd "$PKGDIR"
	#Create .MTREE
	list_package_files | LANG=C bsdtar -cnf - --format=mtree \
		--options='!all,use-set,type,uid,gid,mode,time,size,md5,sha256,link' \
		--null --files-from - --exclude .MTREE | gzip -c -f -n > .MTREE

	if [ -f "$PKGDIR/.INSTALL" ]; then
        tar --xz -cf $CURDIR/$name-$version-$release.pkg.tar.xz * .PKGINFO .BUILDINFO .MTREE .INSTALL
    else
        tar --xz -cf $CURDIR/$name-$version-$release.pkg.tar.xz * .PKGINFO .BUILDINFO .MTREE
    fi
}
